package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"wakitsoft.com/resume/config"
	"wakitsoft.com/resume/models"
)

var db *gorm.DB

func buildDSN(cfg *config.Config) string {
	db := cfg.App.Database
	user := db.User
	password := db.Password
	host := db.Host
	port := db.Port
	name := db.Name
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, name)
}

func InitDB(cfg *config.Config) error {
	opened, err := gorm.Open(mysql.Open(buildDSN(cfg)), &gorm.Config{})
	if err != nil {
		log.Println("init db:", err.Error())
		return err
	}
	db = opened
	if err := opened.AutoMigrate(
		&models.Resume{},
		&models.Media{},
		&models.TechStack{},
		&models.Project{},
		&models.ResumeTechStack{},
		&models.ProjectGallery{},
		&models.ProjectTechStack{},
		&models.WorkExperience{},
		&models.Education{},
		&models.School{},
	); err != nil {
		log.Println("auto migrate:", err.Error())
		return err
	}
	return nil
}

func GetDB() *gorm.DB {
	return db
}
